<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="盘点日期" prop="date">
        <el-date-picker clearable
          v-model="queryParams.date"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择盘点日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="商品" prop="month">
        <el-select v-model="queryParams.fid" placeholder="请选择商品" clearable >
          <el-option
              v-for="item in  fGroup"
              :key="item.fid"
              :label="item.food"
              :value="item.fid"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['shop:date:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['shop:date:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['shop:date:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['shop:date:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="盘点日期" align="center" prop="date" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="foodName" />
      <el-table-column label="上日库存" align="center" prop="lastQuantity"/>
      <el-table-column label="本日进货" align="center" prop="purchaseQuantity" />
      <el-table-column label="本日出货" align="center" prop="sellQuantity" />
      <el-table-column label="本日结存" align="center" prop="balance" />
      <el-table-column label="实际数量" align="center" prop="actualQuantity" />
      <el-table-column label="盘盈盘亏" align="center" prop="profit" />
      <el-table-column label="盘注" align="center" prop="remarks" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['shop:date:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['shop:date:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品日清对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="dateRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="盘点日期" prop="date" >
          <el-date-picker   @change="getData()" clearable
            v-model="form.date"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择盘点日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="商品" prop="status">
          <el-select v-model="form.fid" placeholder="请选择商品" clearable  @change="getData()">
            <el-option
                v-for="item in  fGroup"
                :key="item.fid"
                :label="item.food"
                :value="item.fid"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上日库存" prop="lastQuantity" >
          <el-input v-model="lastQuantity" placeholder="请输入本日进货数量" disabled/>
        </el-form-item>
        <el-form-item label="本日进货" prop="purchaseQuantity" >
          <el-input v-model="purchaseQuantity" placeholder="请输入本日进货数量" :disabled="form.id"/>
        </el-form-item>
        <el-form-item label="本日出货" prop="sellQuantity">
          <el-input v-model="sellQuantity" placeholder="请输入本日出货数量" :disabled="form.id"/>
        </el-form-item>
        <el-form-item label="本日结存" >
          <el-input v-model="balance" placeholder="请输入本日结存数量" :disabled="form.id"/>
        </el-form-item>
        <el-form-item label="盘点数量" prop="actualQuantity">
          <el-input v-model="form.actualQuantity" placeholder="请输入盘点实际数量"    @change="getProfit()"/>
        </el-form-item>
        <el-form-item label="盘盈盘亏"  >
          <el-input v-model="profit" :disabled="form.id" />
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入盘点备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Date">
import {listDate, getDate, delDate, addDate, updateDate, listDate1} from "@/api/shop/date";
import {listFood} from "@/api/shop/food";

const { proxy } = getCurrentInstance();

const dateList = ref([

]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const oData = ref([]);
const fGroup = ref([]);
const purchaseQuantity = ref();
const sellQuantity = ref();
const balance = ref();
const profit= ref();
const lastQuantity= ref();

const data = reactive({
  form: {
  },
  oValue:{
     purchaseTime:null,
     sellTime:null,
     sFoodId:null,
     pFoodId:null
  },

  queryParams: {
    pageNum: 1,
    pageSize: 10,
    date: null,
    fid: null,
    actualQuantity: null,
    remarks: null
  },
  rules: {
    date: [
      { required: true, message: "盘点日期不能为空", trigger: "blur" }
    ],
    fid: [
      { required: true, message: "商品ID不能为空", trigger: "blur" }
    ],
    actualQuantity: [
      { required: true, message: "盘点实际数量不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules, oValue} = toRefs(data);

/** 查询商品日清列表 */
function getList() {
  loading.value = true
  listDate(queryParams.value).then(response => {
    dateList.value = response.rows.map(item => {
      const balance = parseFloat(item.lastQuantity)+parseFloat(item.purchaseQuantity) - parseFloat(item.sellQuantity)
      const profit =  parseFloat(item.actualQuantity)-balance
      return { ...item, balance,profit }
    })
    console.log(dateList.value)
    total.value = response.total
    loading.value = false
  })
}
function getProfit(){
  console.log(oData.value)
  if (form.value.actualQuantity!=null){
    profit.value=parseFloat(form.value.actualQuantity)-oData.value[0].balance
    console.log( profit.value)
  }
}
function getData(){
  sellQuantity.value=null;
  purchaseQuantity.value=null;
  balance.value=null;
  loading.value = true
  oValue.value.purchaseTime=form.value.date
  oValue.value.pFoodId=form.value.fid

  if (oValue.value.purchaseTime != null&& form.value.fid != null){
    listDate1(oValue.value).then(response => {
      oData.value = response.rows.map(item => {
        console.log(oData.value)
        const balance =parseFloat(item.lastQuantity)+ parseFloat(item.purchaseQuantity) - parseFloat(item.sellQuantity)
        return { ...item, balance}
      })
      if(oData.value[0]!=null){
        sellQuantity.value=oData.value[0].sellQuantity;
        purchaseQuantity.value=oData.value[0].purchaseQuantity;
        balance.value=oData.value[0].balance;
        lastQuantity.value=oData.value[0].lastQuantity;
        console.log(lastQuantity.value)
      }
    })
  }

  loading.value = false;
  getList()

}
function getGoods(){
  loading.value = true;
  listFood().then(response =>{
    fGroup.value=response.rows;
  })
  loading.value = false;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    date: null,
    fid: null,
    actualQuantity: null,
    remarks: null
  };
   purchaseQuantity.value = null
   sellQuantity.value = null
   balance.value = null
   profit.value= null
   lastQuantity.value= null
  proxy.resetForm("dateRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.fid=null
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加商品日清";
}

/** 修改按钮操作 */
function handleUpdate(row) {

  reset();
  const _id = row.id || ids.value
  getDate(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改商品日清";
    lastQuantity.value=form.value.lastQuantity
    sellQuantity.value=form.value.sellQuantity
    purchaseQuantity.value=form.value.purchaseQuantity
    balance.value=form.value.lastQuantity+form.value.purchaseQuantity-form.value.sellQuantity
    profit.value=form.value.actualQuantity-balance.value
  });
  console.log(sellQuantity.value)
  console.log(purchaseQuantity.value)

}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["dateRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDate(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDate(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除商品日清编号为"' + _ids + '"的数据项？').then(function() {
    return delDate(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('shop/date/export', {
    ...queryParams.value
  }, `date_${new Date().getTime()}.xlsx`)
}

getGoods()
getList();

</script>
